// ==ClosureCompiler==
// @output_file_name main.min.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// @use_closure_library true
// ==/ClosureCompiler==
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.forms');
goog.require('goog.style');
goog.require('goog.array');
goog.require('goog.userAgent');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Tooltip');
goog.require('goog.ui.AutoComplete');
goog.require('goog.ui.AutoComplete.Basic');
goog.require('goog.ui.AnimatedZippy');
goog.require('goog.ui.PopupDatePicker');
goog.require('goog.i18n.DateTimeSymbols');
goog.require('goog.i18n.DateTimeSymbols_ru');
goog.require('goog.net.XhrIo');

var fs = {
/**
 * базовый URL сайта
 *
 * @var {String}
 */
  baseUrl: [document.location.protocol, document.location.hostname].join("//"),
/**
 * страница, контент которой загружен
 *
 * @var {String}
 */
  hash: document.location.hash,
/**
 * динамическая подгрузка скрипта
 *
 * @param {String} script
 * @return void
 */
  require: function(script){goog.importScript_([this.baseUrl,'/content/js/',script,'.js'].join(''));},
/**
 * загрузка контента во фрейм
 *
 * @param {String} url
 * @return void
 */
  getContent: function(url)
  {
    if (url)
    {
      goog.style.setStyle(document.body, 'cursor', 'progress');
      var params = ['ajax=1'];
      /** @var p {Integer} */
      var p = url.indexOf('?');
      if (0 <= p)
      {
        goog.array.forEach(url.substr(p + 1).split('&'), function(p){p.split('=')[0].iequals('iframe')||params.push(p);});
        url = url.substring(0, p);
      }
      url = [url, params.join('&')].join('?');
    // TODO clear photos
      /** @var frame {Element} */
      var frame = goog.dom.$('ajax-content');
      if (goog.userAgent.IE)
        frame.src = url;
      else
      {
        /** @var fdoc {Document} */
        var fdoc = goog.dom.getFrameContentDocument(frame);
        fdoc && fdoc.location.replace(url);
      }
    }
  },
/**
 * инициализация работы ссылок и загрузка дополнительных скриптов после загрузки контента
 *
 * @param {String} contentId
 * @return void
 */
  contentPrepare: function(contentId)
  {
    contentId = contentId ? ['#', ' '].join(contentId) : '';
    goog.events.listenAll(
      goog.dom.query([contentId, '.link[href]'].join('')),
      goog.events.EventType.CLICK,
      function(e){fs.getContent(this.href.replace(/^#$/,''));e.stopBubble();}
    );
  // TODO execute scripts
    goog.events.listenAll(
      goog.dom.query([contentId, 'a[href="#"]'].join('')),
      goog.events.EventType.CLICK,
      function(e){e.stopBubble();}
    );
  },
/**
 * инициализация по окончании загрузки страницы
 *
 * @return void
 */
  init: function()
  {
    /** @var VK {Object} */
    if (window.VK)
    {
      VK.init({apiId: VK.APP_ID = 2270150});
      VK.Widgets.Group('vk_groups', {mode: 0, width: 400, height: 200}, VK.GROUP_ID = 25396929);
      VK.Share = {count: function(n, count){}};
      VK.createLoginBtn = function(node, callback)
      {
        if (node = goog.dom.$(node))
        {
          VK.UI.button(node.id);
          goog.events.listen(node, goog.events.EventType.CLICK, function(e)
          {
            VK.Auth.login(function(response){response.session&&goog.isFunction(callback)&&callback.call(e.target,e,response.session.user);});
            e.stopBubble();
          });
        }
      };
    }

  // авторизация
    /** @var auth {goog.ui.Dialog} */
    var auth = goog.ui.Dialog.create('auth-dlg', new goog.ui.Dialog.ButtonSet().addButton({key: 'enter', caption: 'Войти'}, true));
    auth.setVisible(true);
    goog.events.listen(auth, goog.ui.Dialog.EventType.SELECT, function(e)
    {
      if (e.key.iequals('enter'))
      {
        goog.dom.forms.validate(goog.dom.$('auth-form'), {submit: function(){}});
        goog.dom.forms.submit(goog.dom.$('auth-form'));
        return false;
      }
    });
    /** @var otherZippy {goog.ui.AnimatedZippy} */
    var otherZippy = null;
    goog.events.listenAll(goog.dom.query('#auth a[href="#login"]'), goog.events.EventType.CLICK, function(e)
    {
      auth.setVisible(true);
      if (!otherZippy)
      {
        /** @var links {Element} */
        var links  = goog.dom.$('other-links');
        otherZippy = new goog.ui.AnimatedZippy(links, 'other-login', false);
        goog.events.listen(links, goog.events.EventType.CLICK, function(e){e.stopBubble();});
        if (window.VK)
          VK.createLoginBtn('vk-login', function(e, user)
          {
            goog.net.XhrIo.send(this.href, function(e)
            {
              /** @var response {Object} */
              var response =  e.target.getResponseJson();
              if (response)
                if (response.errors);
                  // TODO show errors
                  // $fs.error(response.errors.login);
                else
                  response.href && document.location.replace(response.href);
            }, goog.net.XhrIo.methods.POST, ['user[login]=', '&scenario=vkontakte'].join(user.href));
          });
        else
        {
          goog.dom.removeNode(goog.dom.$('vk-login'));
          /** @var other {Element} */
          var other = goog.dom.$('other-login');
          if (!goog.dom.getChildren(other).length)
          {
            goog.dom.removeNode(other);
            goog.dom.removeNode(goog.dom.$('other-links'));
          }
        }
      }
      goog.dom.forms.focusAndSelect(goog.dom.$('login'));
      e.stopBubble();
    });

  // новости по республикам
    /** @var republics {goog.ui.Dialog} */
    var republics = goog.ui.Dialog.create('USSR');
    goog.events.listen(goog.dom.$('republic'), goog.events.EventType.CLICK, function()
    {
      republics.setVisible(true);
      goog.array.forEach(goog.dom.query('map[name="republics"]>area[id]'), function(area)
      {
        goog.ui.Tooltip.create(area, ['<h1 class="republic-name ', area.id, '">', area.alt, '</h1>'].join(''), 'republic-tooltip');
        area.removeAttribute('id');
        goog.events.listen(area, goog.events.EventType.CLICK, function(e)
        {
          goog.dom.setTextContent(goog.dom.$('republic-name'), this.alt);
          republics.setVisible(false);
          e.stopBubble();
        });
      });
    }, true);

  // рубрикатор
    goog.array.forEach(goog.dom.query('#rubric-block>ul>li'), function(li)
    {
      /** @var tags {Element} */
      var tags = goog.dom.getLastElementChild(li);
      goog.dom.classes.has(tags, 'group') && (new goog.ui.AnimatedZippy(goog.dom.getFirstElementChild(li), tags, false));
    });
  // RES PUBLICA
    /** @var rubrics {Element} */
    var rubrics = goog.dom.$('rubrics');
    /** @var rubric {Element} */
    var rubric = goog.dom.$('rubric0');
    goog.dom.appendChild(rubrics, rubric);
    goog.ui.Tooltip.create(rubric, goog.dom.getNodeContent('respublica'));
  // Диаспора
    goog.dom.appendChild(rubrics, rubric = goog.dom.$('rubric-1'));
    goog.ui.Tooltip.create(rubric, goog.dom.getNodeContent('diaspora'));

  // теги
    /** @var tags {Array} */
    var tags = [];
    goog.array.forEach(goog.dom.query('#clouds>a'), function(a){tags.push(goog.dom.getTextContent(a));});
    new goog.ui.AutoComplete.Basic(tags, goog.dom.$('search-text'));

  // календарь
    goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_ru;
    /** @var calendar {goog.ui.DatePicker} */
    var calendar = new goog.ui.PopupDatePicker();
    calendar.render();
    calendar.attach(goog.dom.$('calendar'));
    goog.events.listen(calendar, goog.events.EventType.CHANGE, function()
    {
      // TODO set date filter
      // alert(this.getDate().toString());
    });
    calendar = calendar.getDatePicker();
    calendar.setShowFixedNumWeeks(false);
    calendar.setShowWeekNum(false);
    calendar.setAllowNone(false);
    calendar.setShowToday(false);

  // загрузка контента во фрейм
    goog.events.listen(goog.dom.$('ajax-content'), goog.events.EventType.LOAD, function()
    {
      /** @var doc {Document} */
      var doc = goog.dom.getFrameContentDocument(this);
      if (doc && doc.body)
      {
        /** @var content {Element} */
        var content = goog.dom.$('content');
        content.innerHTML = doc.body.innerHTML;
        goog.array.forEach(goog.dom.$$('a', 'active'), function(a)
        {
          goog.dom.classes.remove(a, 'active');
          a.hasAttribute('url') && (a.href = a.getAttribute('url'));
        });
        goog.array.forEach(goog.dom.query(['a[href="', '"]'].join(fs.hash = doc.location.pathname)), function(a)
        {
          goog.dom.classes.add(a, 'active');
          a.setAttribute('url', fs.hash);
          a.removeAttribute('href');
        });
      // TODO handling toggle
      // $("#handling").toggle(!$("#handling a.active").length);
        document.title = doc.title;
        document.location.href = [document.location.href.replace(/#.*$/, ''), fs.hash].join('#');
        fs.contentPrepare(content.id);
        content.scrollIntoView();
        goog.style.setStyle(document.body, 'cursor', 'auto');
      }
      else
      {
        document.location.hash = '';
        document.location.reload();
      }
    });
    goog.events.listen(window, goog.events.EventType.UNLOAD, function()
    {
    // TODO clear photos
    });
    goog.userAgent.IE || goog.events.listen(window, goog.events.EventType.HASHCHANGE, function()
    {
      /** @var h {String} */
      var h = document.location.hash.replace(/^#/, '');
      h.iequals(fs.hash) || (h ? fs.getContent(h) : document.location.reload());
    });

    this.contentPrepare();
  }
};

fs.require('goog.ext');
fs.require('goog.validate');
